<template>
  <div class="container">
    <van-nav-bar title="餐食饮品" left-text="返回" left-arrow @click-left="back"/>
    <div class="search-bar">
      <van-search v-model="searchQuery" placeholder="搜索菜品" @change="onSearch"/>
    </div>
    <van-tabs v-model:active="activeTab" @click-tab="tabChange">
      <van-tab title="堂食餐" name="1">
        <div v-for="(product, index) in filteredProducts" :key="index" class="product-item">
          <van-image :src="product.image" width="100" height="100"/>
          <div class="product-info">
            <h2 class="product-name">{{ product.name }}</h2>
            <div class="flex a-c j-s">
              <p class="product-price">¥{{ product.price }}</p>
              <div class="product-actions">
                <van-stepper v-model="product.quantity" min="0" @change="updateCart(product)"/>
              </div>
            </div>

          </div>
        </div>
      </van-tab>
      <van-tab title="客房菜" name="2">
        <div v-for="(product, index) in guestRoomData" :key="index" class="product-item">
          <van-image :src="product.image" width="100" height="100"/>
          <div class="product-info">
            <h2 class="product-name">{{ product.name }}</h2>
            <div class="flex a-c j-s">
              <p class="product-price">¥{{ product.price }}</p>
              <div class="product-actions">
                <van-stepper v-model="product.quantity" min="0" @change="updateCart(product)"/>
              </div>
            </div>

          </div>
        </div>
      </van-tab>
    </van-tabs>
    <div class="cart-summary">
      <p>总价：¥{{ totalPrice }}</p>
      <van-button type="primary" block round @click="checkout">立即点单</van-button>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue';
import {useRouter} from "vue-router";
import axios from 'axios';
import {showConfirmDialog, showDialog, Toast} from 'vant';
import {getFood,sendCheckout} from '@/apis/api';


const router = useRouter()

const filteredProducts = ref([]);
const searchQuery = ref('');
const activeTab = ref('dine-in');
const cart = ref([]);
const products = ref([]);
const guestRoomData = ref([])

const fetchProducts = async (type = '1') => {
  try {
    // 传了一个 categroy 你接口打个断点看看哪里可以拿到
    const response = await getFood(
        {category: type}
    );
    if (type === '2') {
      guestRoomData.value = response.map(product => ({...product, quantity: 0}));
    } else if (type === '1') {
      filteredProducts.value = response.map(product => ({...product, quantity: 0}));
    }
  } catch (error) {
    console.error('Error fetching products:', error);
    Toast.fail('加载商品失败');
  }
};

const tabChange = (tab) => {
  console.log(tab)
  fetchProducts(tab.name)
}

const onSearch = () => {
  // 实现搜索逻辑
};

const updateCart = (product) => {
  const cartProduct = cart.value.find(p => p.id === product.id);
  if (product.quantity > 0) {
    if (cartProduct) {
      cartProduct.quantity = product.quantity;
    } else {
      cart.value.push(product);
    }
  } else {
    const index = cart.value.findIndex(p => p.id === product.id);
    if (index !== -1) {
      cart.value.splice(index, 1);
    }
  }
};

let buyLoading = false
const checkout = async () => {
  if(buyLoading)return
  buyLoading = true
  showConfirmDialog({
    title: '提示',
    message: '确认购买吗？',

  })
      .then(async () => {
        //确认
        try {
          const res = await sendCheckout({
            foodCartList: JSON.stringify(cart.value)
          })
          if(res.code===200) {
            initPageData()
            buyLoading = false
            showDialog({
              title: '提示',
              message: '购买成功！',
            });
          }else if(res.code===500){
            showDialog({
              title: '提示',
              message: res.message,
            });
            buyLoading = false
          }
        }catch (e) {
          buyLoading = false
        }
      }).catch(()=>{
    buyLoading = false
        // 取消
  })



  // try {
  // axios({
  //   method: 'post',
  //   url: '/api/checkout',
  //   data: {
  //
  //   }
  // }).then((data) => {
  //   console.log(data, 'data111')
  // });

};

const totalPrice = computed(() => {
  return cart.value.reduce((total, product) => total + product.price * product.quantity, 0);
});

const initPageData = ()=>{
  fetchProducts()
}

// 页面加载渲染数据
onMounted(() => {
  initPageData()
});


// 返回上一页
const back = () => router.back()

</script>

<style scoped>
.product-item {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  margin: 10px 16px;
  padding: 0 12px;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.1);
}

.van-tabs {
  //padding: 0 24px;
}
.container {
  background: #efefef;
}
.flex {
  display: flex;

}
.product-info {
  text-align: left;
  padding: 24px;
}
.van-image {
  border-radius: 8px;
  overflow: hidden;
}
.a-c {
  align-items: center;
}

.j-s {
  justify-content: space-between;
}

.product-info {
  flex: 1;
  margin-left: 10px;
}

.product-name {
  font-size: 18px;
  margin: 5px 0;
}

.product-price {
  color: #f44;
}

.product-actions {
  //margin-top: 10px;
}

.cart-summary {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
}
</style>
